<template>
  <input
    :type="type"
    v-if="!autoSize"
    :placeholder="placeholder"
    :min="min"
    :max="max"
    :maxlength="maxlength"
    :value="value"
    @input="syncModelValue"
  />
  <div
    v-else
    class="input-div"
    :class="[autoSize === 'width' ? 'width' : 'height']"
    tabindex="1"
    contenteditable="true"
    :data-text="placeholder"
    :innerText="value"
    @input="syncModelValue"
  ></div>
</template>

<script lang='ts'>
import { reactive, toRefs } from "vue";
export default {
  name: "YInput",
  props: {
    modelValue: {
      default: "",
      type: String,
    },
    type: {
      default: "text",
      type: String,
    },
    placeholder: {
      default: "",
      type: String,
    },
    min: {
      default: 0,
      type: Number,
    },
    max: {
      default: 100000,
      type: Number,
    },
    maxlength: {
      default: 1000000,
      type: Number,
    },
    autoSize: {
      default: "", // width是水平拓展尺寸，height是垂直扩展尺寸
      type: String,
    },
  },
  setup(props: any, attrs: any) {
    const state = reactive({
      value: "",
    });
    // eslint-disable-next-line vue/no-setup-props-destructure
    state.value = props.modelValue;
    const syncModelValue = (e: any) => {
      const { emit } = attrs;
      const text = props.autoSize ? e.target.innerText : e.target.value;
      state.value = text;
      emit("update:modelValue", text);
    };
    return {
      ...toRefs(state),
      syncModelValue,
    };
  },
};
</script>

<style lang='scss'>
input {
  padding: 8px 12px;
  width: 200px;
  border: 0;
  outline: none;
  border: 1px solid #0095ff;
  font-size: 15px;
  &:focus {
    border: 1px solid #0957e7;
  }
  &::-webkit-input-placeholder {
    color: #999;
  }
}
.input-div {
  display: inline-block;
  padding: 8px 12px;
  -webkit-user-modify: read-write-plaintext-only;
  border: 1px solid #0095ff;
  color: #000;
  outline: none;
  text-align: left;
  font-size: 15px;
  height: 20px;
  line-height: 20px;
  &:focus {
    border: 1px solid #0957e7;
  }
  &.width {
    min-width: 200px;
    overflow-y: hidden;
    overflow-x: auto;
    height: auto;
    background: #fff;
  }
  &.height {
    width: 200px;
    height: auto;
    min-height: 20px;
    overflow-y: auto;
    overflow-x: hidden;
    background: #fff;
  }
}
[contentEditable="true"]:empty:not(:focus):before {
  color: #999;
  content: attr(data-text); // 核心
  font-size: 15px;
}
</style>